package cn.wildfire.chat.app.extendsion.ui;

import android.app.Dialog;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.kit.common.OperateResult;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfire.chat.kit.third.utils.FileUtils;
import cn.wildfirechat.message.MessageContentMediaType;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GeneralCallback2;

/**
 * Create by HEKE, 2019/8/24 3:02
 * TODO 群组创建前设置参数窗口
 */
public class GroupCreateSettingsDialog extends Dialog {

    public static final int CREATE_NORMAL = 0x00;
    public static final int CREATE_LIVEDATAS = 0x01;

    protected GroupViewModel groupViewModel;
    protected List<UIUserInfo> userInfos;
    protected LifecycleOwner owner;
    protected OnCreateGroupListener onCreateGroupListener;
    protected int type = CREATE_NORMAL;

    @BindView(R2.id.groupIcon)
    ImageView groupIcon;
    @BindView(R2.id.groupnameEdit)
    EditText groupnameEdit;
    @BindView(R2.id.groupSetCancle)
    Button groupSetCancle;
    @BindView(R2.id.groupSetConfirm)
    Button groupSetConfirm;

    /**
     * 头像数据
     */
    private byte[] portraitContent;

    public GroupCreateSettingsDialog(@NonNull Context context, List<UIUserInfo> userInfos,
                                     GroupViewModel groupViewModel, int type, OnCreateGroupListener onCreateGroupListener) {
        super(context, R.style.transparentDiag);
        this.userInfos = userInfos;
        this.groupViewModel = groupViewModel;
        this.type = type;
        this.onCreateGroupListener = onCreateGroupListener;
        checkSelf();
    }

    public GroupCreateSettingsDialog(@NonNull Context context, List<UIUserInfo> userInfos,
                                     GroupViewModel groupViewModel, int type, LifecycleOwner owner, OnCreateGroupListener onCreateGroupListener) {
        super(context, R.style.transparentDiag);
        this.userInfos = userInfos;
        this.groupViewModel = groupViewModel;
        this.type = type;
        this.owner = owner;
        this.onCreateGroupListener = onCreateGroupListener;
        checkSelf();
    }

    private void initWindow() {
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.x = 0;
        layoutParams.y = 0;
        layoutParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);
        loadDatas();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (groupnameEdit != null) {
            groupnameEdit.setFocusable(true);
            groupnameEdit.setFocusableInTouchMode(true);
            groupnameEdit.setCursorVisible(true);
            groupnameEdit.requestFocus();
            groupnameEdit.requestLayout();
            CaiBaChatApp.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showInputMethod();
                }
            }, 200);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_group_create_settings);
        ButterKnife.bind(this);
        initWindow();
    }

    /**
     * 检测自身是否包含
     */
    private void checkSelf() {
        // 判断是否包含自身信息
        try {
            ChatManager chatManager = ChatManager.Instance();
            UserInfo self = chatManager.getUserInfo(chatManager.getUserId(), false);
            if (userInfos != null) {
                boolean contains = false;
                for (UIUserInfo userInfo : userInfos) {
                    if (userInfo.getUserInfo().uid.equals(self.uid)) {
                        contains = true;
                        break;
                    }
                }
                if (!contains) {
                    this.userInfos.add(new UIUserInfo(self));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载数据
     */
    private void loadDatas() {
        createGroupPortrait();
    }

    /**
     * 创建群组头像
     */
    public String createGroupPortrait() {
        String portraitPath = "";
        try {
            ChatManager.Instance().getWorkHandler().post(() -> {
                String groupPortrait = null;
                try {
                    groupPortrait = groupViewModel.generateGroupPortrait(getContext(), userInfos);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (groupPortrait != null) {
                    byte[] content = FileUtils.readFile(groupPortrait);
                    portraitContent = content;
                    CaiBaChatApp.getMainHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            groupIcon.setImageBitmap(BitmapFactory.decodeByteArray(portraitContent, 0, portraitContent.length));
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return portraitPath;
    }

    /**
     * 创建群组名称
     *
     * @param customGroupName
     * @return
     */
    public String createGroupName(String customGroupName) {
        String groupName = "";
        try {
            if (!cn.wildfire.chat.app.extendsion.utils.TextUtils.isTextEmpty(customGroupName)) {
                groupName = customGroupName;
            } else {
                if (userInfos.size() > 3) {
                    for (int i = 0; i < 3; i++) {
                        UserInfo friend = userInfos.get(i).getUserInfo();
                        groupName += friend.displayName + "、";
                    }
                } else {
                    for (UIUserInfo friend : userInfos) {
                        groupName += friend.getUserInfo().displayName + "、";
                    }
                }
                groupName = groupName.substring(0, groupName.length() - 1);
                if (groupName.length() >= 28) {
                    groupName = userInfos.get(0).getUserInfo().displayName + "等";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupName;
    }

    @OnClick({R2.id.groupSetCancle, R2.id.groupSetConfirm})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.groupSetCancle) {
            dismiss();
        } else if (id == R.id.groupSetConfirm) {
            createGroup();
        }
    }

    /**
     * 获取群组所有成员编号列表
     *
     * @param addSelf
     */
    private ArrayList<String> getGroupIds(boolean addSelf) {
        if (userInfos == null)
            return null;
        ArrayList<String> selectedIds = new ArrayList<>();
        for (UIUserInfo userInfo : userInfos) {
            selectedIds.add(userInfo.getUserInfo().uid);
        }
        if (addSelf) {
            selectedIds.add(ChatManager.Instance().getUserId());
        }
        return selectedIds;
    }

    /**
     * 弱网防护设置
     */
    protected boolean createGroupLock;
    protected MaterialDialog dialog;

    /**
     * TODO 创建群聊
     */
    private void createGroup() {
        try {
            if (!createGroupLock) {
                createGroupLock = true;

                dialog = new MaterialDialog.Builder(getContext())
                        .content("创建中...")
                        .progress(true, 100)
                        .cancelable(false)
                        .build();
                dialog.show();

                String groupNameSet = groupnameEdit.getText().toString();
                String groupName = createGroupName(groupNameSet);
                if (portraitContent == null) {
                    Toast.makeText(getContext(), "请等待头像加载完毕!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (type == CREATE_NORMAL) {
                    ChatManager.Instance().uploadMedia(portraitContent, MessageContentMediaType.PORTRAIT.getValue(), new GeneralCallback2() {
                        @Override
                        public void onSuccess(String result) {
                            ChatManager.Instance().createGroup(null, groupName, result, GroupInfo.GroupType.Restricted, getGroupIds(false),
                                    Arrays.asList(0), null, new GeneralCallback2() {
                                        @Override
                                        public void onSuccess(String groupId) {
                                            if (onCreateGroupListener != null) {
                                                onCreateGroupListener.result(true, groupId);
                                            }
                                            gone();
                                        }

                                        @Override
                                        public void onFail(int errorCode) {
                                            if (onCreateGroupListener != null) {
                                                onCreateGroupListener.result(false, null);
                                            }
                                            gone();
                                        }
                                    });
                        }

                        @Override
                        public void onFail(int errorCode) {
                            if (onCreateGroupListener != null) {
                                onCreateGroupListener.result(false, null);
                            }
                            gone();
                        }
                    });
                } else if (type == CREATE_LIVEDATAS) {
                    groupViewModel.createGroup(getContext(), userInfos, groupName)
                            .observe(owner, new Observer<OperateResult<String>>() {
                                @Override
                                public void onChanged(@Nullable OperateResult<String> result) {
                                    if (onCreateGroupListener != null) {
                                        onCreateGroupListener.datasResult(result);
                                    }
                                    gone();
                                }
                            });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭窗口
     */
    private void gone() {
        createGroupLock = false;
        if (dialog != null) {
            dialog.dismiss();
        }
        CaiBaChatApp.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                dismiss();
            }
        });
    }

    /**
     * 输入法弹出与隐藏
     */
    private void showInputMethod() {
        InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * Create by HEKE, 2019/8/24 3:20
     * TODO 创建回调接口
     */
    public interface OnCreateGroupListener {
        void result(boolean created, String target);

        void datasResult(OperateResult<String> result);
    }

}
